<?php

namespace App\Api\Controllers;


use App\Api\Requests\RegisterAuthRequest;
use App\Models\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use luochuan\JWTAuth\Exceptions\JWTException;
use luochuan\JWTAuth\Facades\JWTAuth;


class UserController extends BaseController
{
    public $loginAfterSignUp = true;
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;


    public function register(RegisterAuthRequest $request)
    {

        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);


        if($user->save()){
            $input = $request->only('email', 'password');
            //token获取失败时
            if(!$jwt_token = JWTAuth::attempt($input)){
                return response()->fail(702);
            }
            $user['token'] = $jwt_token;
            return response()->success($user,'','注册成功啦');
        }else{
            return response()->fail(701);
        }


    }

    public function login(Request $request)
    {
        $input = $request->only('email', 'password');
        $jwt_token = null;

        if (!$jwt_token = JWTAuth::attempt($input)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid Email or Password',
            ], 401);
        }

        return response()->success([
            'success' => true,
            'user'=>auth()->user(),
            'token' => $jwt_token,
        ]);
    }
    public function logout(Request $request)
    {
        $this->validate($request, [
            'token' => 'required'
        ]);

        try {
            JWTAuth::invalidate($request->token);

            return response()->json([
                'success' => true,
                'message' => 'User logged out successfully'
            ]);
        } catch (JWTException $exception) {
            return response()->json([
                'success' => false,
                'message' => 'Sorry, the user cannot be logged out'
            ], 500);
        }
    }
    public function getUser(Request $request)
    {

//        $this->validate($request, [
//            'token' => 'required'
//        ]);

        $user = JWTAuth::authenticate($request->token);

        return response()->json(['user' => $user]);
    }
}
